<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Search extends MY_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('contact_model');	
		$this->load->model('company_model');	
		$this->load->model('titles_model');	
        $this->load->model('flag_model');
        $this->load->model('mail_model');
        $this->load->model('previous_event_model', 'pevent');
	}
	
	public function index()
	{
		$data['com_list'] 	= $this->company_model->where('deleted',0)->find_all();
		$data['con_list'] 	= $this->contact_model->where('deleted',0)->find_all();
        $data['flag_list'] 	= $this->flag_model->where('deleted',0)->find_all();
        $data['pevent_list'] 	= $this->pevent->find_all();
		$data['title_list']     = $this->titles_model->where('deleted',0)->find_all();
		
		$this->load->view('search/main', $data);
	}
	
	//Company Table View
	public function company($get_list=False)
	{
		if($get_list)
		{
			$data	 = $this->db->where('deleted',false)->get('company')->result();
			$i = 0;
			foreach($data as $row):
				$r['aaData'][$i]['box'] = "<input type='checkbox' onClick='addToList(this.value)'  name='checkbox[]' id='check_{$row->id}' value='{$row->id}' title='{$row->name}' />";
				$r['aaData'][$i]['name'] = $row->name;
				$r['aaData'][$i]['Flags'] = "";
				$flags = $this->flag_model->get_flag_company($row->id);
				if($flags):
				foreach($flags as $flag):
					$r['aaData'][$i]['Flags'].= $flag->name_en."<br>";
				endforeach;
				endif;
				$countries = $this->config->item('en_countries');
				$r['aaData'][$i]['Country'] = "({$row->country}/{$row->city})<br>";
				if(isset($row->country) && !empty($row->country)) 
					$r['aaData'][$i]['Country'].= "<img src='{$this->config->item('images')}/flags/{$row->country}.gif' /> <br>".$countries[$row->country];
				
				$r['aaData'][$i]['Phone'] = $row->phone1.' '.$row->phone2.' '.$row->phone3.' '.$row->fax1;
				$r['aaData'][$i]['notes'] = "<a href='javascript:;' onClick='full_d({$row->id})'>Show Full D.</a>";
				$r['aaData'][$i]['other'] ="<div id='td_{$row->id}'>
										<p id='tdname'><b>{$row->name}</b></p>
										<p>{$row->address1}</p>
										<p>{$row->address2}</p>
										<p>{$row->website}</p>
										<p>{$row->email}</p>
										<p>{$row->notes}</p>
										</div>";
				$i++;
			endforeach;	
			die(json_encode($r));
		}
		$data['mail_templates']  = $this->db->get('mail_template')->result();
		$this->load->view('search/table_company',$data);
	}
	
	function com_list($action)
	{

		$data['ids'] = $this->input->post('list');
		/*
		foreach($data['ids'] as $row)
			$this->db->or_where('company.id',$row);
		
		$this->db->where('company.deleted',false);		
		*/
		
		$this->log('Search', 'Action/Company ('.$action.') for (IDs: ) '.$this->session->userdata['ip_address']);
		Switch($action):
			
			case 'export':
				$this->load->library('Pdf');
				
				foreach($data['ids'] as $row)
					$this->db->or_where('company.id',$row);
				
				$this->db->where('company.deleted',false);
				$list = $this->db->get('company');
				
				$pdf = $this->pdf->pdf_table_company($list->result());
				$xx['msg'] = ($pdf==null ? 'Success' : 'Error');
				$xx['name'] = $pdf;
					
				die(json_encode($pdf));
			break;
			
			case 'mail':
				$lang 		= $this->input->post('lang');
				$template 	= $this->input->post('template');
				
				$this->load->library('email');
				$result = $this->mail_model->send_to($data);
				
				$mail = $this->email->send_mass($result->result(), $lang, $template);
				//$xx['msg'] = ($pdf==null ? 'Success' : 'Error');
				
				if(!$mail)	
					die('No Data Found');
					
				die(json_encode($mail));
			break;
			
		Endswitch;
		
		//$data['action'] = $action;
		//die(json_encode($data));
	}
	
	function con_list($action)
	{
		$this->log('Search', 'Action/Contacts ('.$action.') for (IDs: ) '.$this->session->userdata['ip_address']);
		
		$data['ids'] = $this->input->post('list');
		
		foreach($data['ids'] as $row)
			$this->db->or_where('contacts.id',$row);
		
		$this->db->where('contacts.deleted',false);		
		
		
		Switch($action):
			
			case 'export':
				$this->load->library('Pdf');
				
				$this->db->select('contacts.*, company.name as com, titles.name as title_ar, titles.en_name as title_en');
				$this->db->join('titles', 'contacts.title = titles.id' ,'left');
				$this->db->join('company', 'contacts.company = company.id' ,'left');
				
				$list = $this->db->get('contacts');
				//print_r($this->db->last_query());
				$pdf = $this->pdf->pdf_table_contact($list->result());
				$xx['msg'] = ($pdf==null ? 'Success' : 'Error');
				$xx['name'] = $pdf;
					
				die(json_encode($pdf));
			break;
			
			case 'mail':
				$lang 		= $this->input->post('lang');
				$template 	= $this->input->post('template');
				
				$this->load->library('email');
				$result = $this->mail_model->send_to($data);

				$mail = $this->email->send_mass($result->result(), $lang, $template);
				//$xx['msg'] = ($pdf==null ? 'Success' : 'Error');
				die(json_encode($mail));
				/*
				$this->db->select('contacts.id as con_id, contacts.email, titles.name as title, contacts.name_ar,company.email as com_mail, company.name as com_name');
				$this->db->from('contacts');
				$this->db->join('company' ,'company.id = contacts.company');
				$this->db->join('titles' ,'titles.id = contacts.title');
				$this->db->where('contacts.deleted',false);		
				$list = $this->db->get();
				
				//print_r($this->db->last_query());
				//print_r($list->result());
				//die;
				$mail = $this->mail($list->result());
				//$xx['msg'] = ($pdf==null ? 'Success' : 'Error');
					
				die(json_encode($mail));
				*/
			break;
			
		Endswitch;
		
		//$data['action'] = $action;
		//die(json_encode($data));
	}
	
	//Contacts Table View
	// $get_list is used to return all the data in contacts table joined with al other tabels
	// if set as a true then it will return a sjon array (used only with ajax)
	// else if set to false return the view of the contact search with empty data
	// this should reduse the load time and make the browser more confy
	public function contact($get_list=False)
	{
		$data	 = $this->db->where('deleted',false)->get('company')->result();
		
		if($get_list)
		{
			$this->db->select('contacts.*, company.id as com_id, company.name as com_name, titles.name as title_ar, titles.en_name as title_en, previous_event.event_name');
			$this->db->where('contacts.deleted',false);
			$this->db->join('company','contacts.company = company.id','left');
			$this->db->join('titles','contacts.title = titles.id','left');
			$this->db->join('previous_event','contacts.previous_event = previous_event.id','left');
			$data  =$this->db->get('contacts')->result();
			
			$i = 0;
			foreach($data as $row):
				$r['aaData'][$i]['box'] = "<input type='checkbox' onClick='addToList(this.value)'  name='checkbox[]' id='check_{$row->id}' value='{$row->id}' title='{$row->name_en}' />";
				$r['aaData'][$i]['name'] = $row->title_ar.' '.$row->name_ar.'<br>'.$row->title_en.' '.$row->name_en;
				$r['aaData'][$i]['Flags'] = "";
				$flags = $this->flag_model->get_flag_contact($row->id);
				if($flags):
				foreach($flags as $flag):
					$r['aaData'][$i]['Flags'].= $flag->name_en."<br>";
				endforeach;
				endif;
				
				$r['aaData'][$i]['Job'] = $row->job_des;
				$r['aaData'][$i]['Country'] = "({$row->country}/{$row->city})<br>";
				$countries = $this->config->item('en_countries');
				if(isset($row->country) && !empty($row->country)) 
				$r['aaData'][$i]['Country'].= "<img src='{$this->config->item('images')}/flags/{$row->country}.gif' /> <br>".$countries[$row->country];
				$r['aaData'][$i]['Phone'] = $row->mobile1.' '.$row->mobile2.' '.$row->home_phone.' '.$row->fax;
				$r['aaData'][$i]['email'] = $row->email;
				$r['aaData'][$i]['full'] = "<a href='javascript:;' onClick='full_d({$row->id})'>Show Full D.</a>";
				$r['aaData'][$i]['other'] ="<div id='td_{$row->id}'>
										<p id='tdname'>Name: {$row->name_ar}</p>
										<p>Company Name: {$row->com_name}</p>
										<p>Lang: {$row->lang}</p>
										<p>{$row->website}</p>
										<p>{$row->email}</p>
										<p>{$row->event_name}</p>
										<p>{$row->notes}</p>
										<p>{$row->extra}</p>
										<p>{$row->extra_2}</p>
										<p>{$row->extra_3}</p>
										</div>";
				$i++;
			endforeach;	
			die(json_encode($r));
		}
		
		$data['mail_templates']  = $this->db->get('mail_template')->result();
		$this->load->view('search/table_contact',$data);
	}
	
	function filter()
	{
		//company only
		$data['allcompany'] 	= $this->input->post('allcompany');
		$data['company_part'] 	= strtolower($this->input->post('company_part'));
		
		//contacts only
		$data['allcontact'] 	= $this->input->post('allcontact');
		$data['contact_part'] 	= $this->input->post('contact_part');
		$data['job_des'] 		= $this->input->post('job_des');
		$data['jobdes_part'] 	= $this->input->post('jobdes_part');
		$data['lang'] 			= $this->input->post('lang');
		$data['title'] 			= $this->input->post('title');
		$data['gender'] 		= $this->input->post('gender');
		$data['history'] 		= $this->input->post('history');
		
		//common
		$data['city'] 			= $this->input->post('city');
		$data['country'] 		= $this->input->post('country');
		$data['flag'] 			= $this->input->post('flag');
		$data['notes'] 			= $this->input->post('notes');
		$data['num'] 			= $this->input->post('num');
		$data['number_part'] 	= $this->input->post('number_part');
		$data['pevent_part'] 	= $this->input->post('pevent_part');
		$data['previous_event'] = $this->input->post('previous_event');
		$data['rate'] 			= $this->input->post('rate');
		$data['rate_op'] 		= $this->input->post('rate_op');
		$data['website'] 		= $this->input->post('website');
		$data['website_part'] 	= $this->input->post('website_part');

		//company query
		$this->db->distinct();
		$this->db->select(" company.* ");
		$this->db->where('company.deleted',false);
		
		
		
		
		if(isset($data['company_part']) && $data['company_part']!='')
			$this->db->where('LOWER(company.name) like binary "%'.$data['company_part'].'%"');

		$count = count($data['allcompany']);
		
		for($i=0; $i<$count; $i++){
			if($data['allcompany'][$i]!=NULL)
				$this->db->where('company.id', $data['allcompany'][$i]);
		}
		
		if($data['city']!='')
			$this->db->where('LOWER(company.city) like binary "%'.$data['city'].'%"');
		

		$count = count($data['country']);
		for($i=0; $i<$count; $i++){
			if($data['country'][$i]!=NULL)
				$this->db->where('company.country', $data['country'][$i]);
		}

		if(is_array($data['flag'])){
			$count = count($data['flag']);

			if($count>=1)
				$this->db->join('flag_company', 'flag_company.company_id = company.id');
			for($i=0; $i<$count; $i++){
				if($data['flag'][$i]!=NULL)
					$this->db->where('flag.id', $data['flag'][$i]);					
			}
			for($i=0; $i<$count; $i++){
				if($data['flag'][$i]!=NULL)
					$this->db->or_where('flag_company.flag_id',$data['flag'][$i]);
			}
			$this->db->select('flag.*');
			$this->db->join('flag', 'flag_company.flag_id = flag.id');
			
		}
		
		$this->db->from('company');
		
		
		$com_query = $this->db->get();
		$result['result'] = $com_query->result_array();
		$result['lq'] = $this->db->last_query();
		$result['count'] = count($result['result']);
		//print_r($com_query->result_array());
		//print_r($this->db->last_query());
		die(json_encode($result));
	}
	

	
}
